package com.citcc.api.netty.server;


import com.citcc.api.controller.PayNotifyController;
import com.citcc.api.netty.EchargeConstants;
import com.citcc.api.netty.bean.ConsuMessage;
import com.citcc.api.netty.utils.BitUtil;
import com.citcc.api.netty.utils.HexUtil;
import com.citcc.business.bean.*;
import com.citcc.business.service.*;
import com.citcc.business.util.CollectionUtil;
import com.citcc.business.util.IdGenerator;
import com.citcc.common.jpush.PushUtil;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 基于netty3的JT809协议验证实现。程序可以接收下级平台发送的业务报文，并转换成POJO对象。程序只处理了两个业务类型：下级平台登录、主链路连接保持消息。没有实现从链路的建立。

数据流：下级平台-->LoggingHandler-->Decoder-->Message-->BusiHandler-->Message-->Encoder-->LoggingHandler-->下级平台。
[list]
[*]LoggingHandler是Netty框架提供的日志Handler，可以在控制台显示出站、入站的数据，方便调试。
[*]Decoder负责报文数据的完整性处理，并转换字节流为报文POJO对象。
[*]Message为自定义的JT809协议POJO对象
[*]BusiHandler为业务处理类
[*]Encoder负责将报文POJO对象拼装成ChannelBuffer对象传输
[*]Util.crc16是从网上找的CRC校验方法
[/list]

[u][i]由于是技术验证，代码中的一些值是写死的。
 * @author think
 *
 */
@SuppressWarnings("all")
public class ServerHandler extends SimpleChannelHandler {
    private Logger log = LoggerFactory.getLogger(ServerHandler.class);
    
    //处理充电桩业务
    public static CdzStakeService cdzStakeService;
    
    //处理充电枪业务
    public static CdzGunService cdzGunService;
    
    //订单业务
    public static CdzIndentService cdzIndentService;
    
    public static CdzAppUserService cdzAppUserService;
    
    // 扩展
 	public static ScanCodeService scanCodeService;
 	
    // 充电信息
  	public static CdzChargingService cdzChargingService;
  	
    // 警告信息
   	public static CdzWarnService cdzWarnService;
   	
    // 桩信息
   	public static CdzStationService cdzStationService;
   	
    // 费率信息
   	public static CdzRatesService cdzRatesService;
   	
   	public static PayNotifyController payNotifyController;
   	
   	public static CdzOrderRefundService cdzOrderRefundService;
   	
   	public static CdzAmountDetailService cdzAmountDetailService;

    
    private static String charging_status = "0";//充电中
    private static String not_charging_status = "1";//未充电
    private static String finish_charging_status = "2";//已完成
    
    
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        ConsuMessage msg = (ConsuMessage) e.getMessage();
        InetSocketAddress address = (InetSocketAddress)ctx.getChannel().getRemoteAddress();
        int port = address.getPort(); //得到的是客户端绑定的port
        String add = address.getAddress().toString();
        String req = add+":"+port;
        log.info("服务端接收到数据[{}]",msg.toString());
        log.info("服务端接收到命令0x"+Integer.toHexString(msg.getMsgId())+"-->终端号:"+msg.getDeviceNo());
        if(StringUtils.isBlank(msg.getMsgId()+"") || StringUtils.isBlank(msg.getDeviceNo()+"")){
        	return;
        }
        long bwHexDeviceNo = msg.getDeviceNo();
    	//转16进制
    	String hex = Long.toHexString(bwHexDeviceNo);
    	//高低互换
    	String hlHex = HexUtil.hexHighLow(hex);
    	Long deviceNo = Long.valueOf(hlHex, 16);
        switch (msg.getMsgId()) {
            case 0x02://登录
            	log.info("接收到客户端登录请求时:-设备号:"+deviceNo);
            	
            	CdzStake cdzs = cdzStakeService.getCdzStakeByStakeCode(deviceNo+"");
            	CdzStake cdzStake = new CdzStake();
            	
            	//Thread.sleep(29000);
                if(cdzs !=null){
                	cdzStake.setId(cdzs.getId());
                	cdzStake.setIsOnline("1");//在线
                	long s = System.currentTimeMillis();
                	//放入map
                    ChannelMap.addChannel(""+deviceNo, e.getChannel());
                    TerminalAddressMap.addAddress(req,deviceNo+"");// key:地址    value:桩号
                    responseLogin(msg,ctx,e, EchargeConstants.LOGIN_SUCCESS_C);
                    log.info("请求地址"+req+"-->设备号==============="+deviceNo+"-->登录成功"+"----链接状态:"+e.getChannel().isConnected()+"-->开启状态:"+e.getChannel().isOpen()+"-->耗时:"+(System.currentTimeMillis()-s));
                    log.info("充电桩在线channel数量="+ChannelMap.getNum());
                    //更新充电桩的在线状态
                    //cdzGunService.updateOnLine(cdzStake);
                }else{
                	log.info("设备号==============="+deviceNo+"-->登录失败");
                    //响应登录失败
                    responseLogin(msg,ctx,e,EchargeConstants.LOGIN_FAIL_C);
                }
                break;
            case 0x01:
            	//心跳请求接收和响应
                responseHeart(msg,ctx,e);
                break;
            case 0x03:
            	log.info("接收到客户端退出请求时:-设备号:"+deviceNo);
            	int res = ChannelMap.removeChannelByName(deviceNo+"");
            	if(res==0){
            		log.info("接收到客户端退出请求时:-设备号:"+deviceNo+"-->退出成功");
            		responseLogout(msg,ctx,e,EchargeConstants.LOGOUT_SUCCESS_C);
            	}else{
            		log.info("接收到客户端退出请求时:-设备号:"+deviceNo+"-->设备不在线");
            		responseLogout(msg,ctx,e,EchargeConstants.LOGOUT_FAIL_C);
            	}
                break;
            case 0x10:
            	//启动命令的响应
                System.out.println("msg:" + msg.toString());
                receiveResp(msg);
                break;
            case 0x14:
            	//客户端实时数据的接收处理和响应
                handleRealTimeData(msg,ctx,e,EchargeConstants.UPLOAD_REAL_TIME__C);
                break;
            case 0x06:
            	//客户端历史数据的接收处理和响应
                handleHistoryData(msg,ctx,e,EchargeConstants.UPLOAD_HISTORY_C);
                break;
            case 0x07:
            	//客户端告警信息数据的接收处理和响应
                handleWarnData(msg,ctx,e,EchargeConstants.UPLOAD_HISTORY_C);
                break;
            case 0x41:
            	//浮点费率
                fl(msg,ctx,e,EchargeConstants.UPLOAD_FL__C);
                break;
            default:
                break;
        }
    }
    
    

    @Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.exceptionCaught(ctx, e);
		if(!e.getChannel().isConnected() && !e.getChannel().isOpen()){
			e.getChannel().close();
		}
		
        log.warn("=======exceptionCaught=======");
	}



	//封装登录响应数据体
    private void responseLogin(ConsuMessage msg, ChannelHandlerContext ctx, MessageEvent e,int c) {
        ChannelBuffer bodyBuffer = ChannelBuffers.buffer(14);
        bodyBuffer.writeShort(0x1300);//长度
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(Long.toHexString(msg.getDeviceNo())));//终端号
        bodyBuffer.writeByte(msg.getMsgId());//登录命令
        int s = msg.getSource();
        int qh = s-16;
        String frame = Integer.toHexString(s);
        if ("10".equals(frame)) {
            bodyBuffer.writeByte(0x00);//1帧来源+枪号
        }else if("11".equals(frame)) {
            bodyBuffer.writeByte(0x01);//1帧来源+枪号
        }else if("12".equals(frame)) {
            bodyBuffer.writeByte(0x02);//1帧来源+枪号
        }else if("13".equals(frame)) {
            bodyBuffer.writeByte(0x03);//1帧来源+枪号
        }

        bodyBuffer.writeByte(0x01);//应答  0.请求帧，1.应答帧，2.主动上传
        bodyBuffer.writeByte(c);//1.确认
        bodyBuffer.writeInt(0x01070502);//版本
        msg.setMsgBody(bodyBuffer);

        e.getChannel().write(msg);

    }
    
    //封装退出响应数据体
    private void responseLogout(ConsuMessage msg, ChannelHandlerContext ctx, MessageEvent e,int c) {
        ChannelBuffer bodyBuffer = ChannelBuffers.buffer(14);
        bodyBuffer.writeShort(0x1500);//长度
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(Long.toHexString(msg.getDeviceNo())));//终端号
        bodyBuffer.writeByte(msg.getMsgId());//退出命令
        int s = msg.getSource();
        int qh = s-16;
        String frame = Integer.toHexString(s);
        if ("10".equals(frame)) {
            bodyBuffer.writeByte(0x00);//1帧来源+枪号
        }else if("11".equals(frame)) {
            bodyBuffer.writeByte(0x01);//1帧来源+枪号
        }else if("12".equals(frame)) {
            bodyBuffer.writeByte(0x02);//1帧来源+枪号
        }else if("13".equals(frame)) {
            bodyBuffer.writeByte(0x03);//1帧来源+枪号
        }

        bodyBuffer.writeByte(0x01);//应答  0.请求帧，1.应答帧，2.主动上传
        bodyBuffer.writeByte(c);//1.确认
        bodyBuffer.writeInt(0x01070502);//版本
        msg.setMsgBody(bodyBuffer);

        e.getChannel().write(msg);
        log.info("响应客户端的退出请求-----------");

    }



    //封装心跳响应数据体
    private void responseHeart(ConsuMessage msg, ChannelHandlerContext ctx, MessageEvent e) {
    	InetSocketAddress address = (InetSocketAddress)ctx.getChannel().getRemoteAddress();
        int port = address.getPort(); //得到的是客户端绑定的port
        String add = address.getAddress().toString();
        String req = add+":"+port;
    	//TODO  判断是否存在该终端号  
    	long bwHexDeviceNo = msg.getDeviceNo();
    	
    	//转16进制
    	String hex = Long.toHexString(bwHexDeviceNo);
    	//高低互换
    	String hlHex = HexUtil.hexHighLow(hex);
    	Long deviceNo = Long.valueOf(hlHex, 16);
    	Channel channel = ChannelMap.getChannelByName(deviceNo + "");
    	if(channel!=null){
    		log.warn("从map中获取到终端号:"+deviceNo+"--------->连接状态:"+channel.isConnected()+"-->开启状态:"+channel.isOpen());
    	}
    	Channel chanel = e.getChannel();
    	if(chanel!=null){
    		ChannelMap.addChannel(""+deviceNo, chanel);
    		TerminalAddressMap.addAddress(req,deviceNo+"");// key:地址    value:桩号
    		log.warn("请求地址:"+req+"-->终端号:"+deviceNo+"--------->连接状态:"+chanel.isConnected()+"-->开启状态:"+chanel.isOpen());
    	}else{
    		log.warn("终端号:"+deviceNo+"--------->chanel空");
    		e.getChannel().close();
    	}
    	
    	int s = msg.getSource();
    	int qh = s-16;
    	log.info("接收到客户端发送的心跳请求时:-设备号:"+deviceNo+"-->枪号:"+qh);
        ChannelBuffer bodyBuffer = ChannelBuffers.buffer(10);
        bodyBuffer.writeShort(0x0F00);//15  不足末尾补00
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(Long.toHexString(msg.getDeviceNo())));//终端号
        bodyBuffer.writeByte(msg.getMsgId());//心跳命令
        
        String frame = Integer.toHexString(s);
        if ("10".equals(frame)) {
            bodyBuffer.writeByte(0x00);//1帧来源+枪号
        }else if("11".equals(frame)) {
            bodyBuffer.writeByte(0x01);//1帧来源+枪号
        }else if("12".equals(frame)) {
            bodyBuffer.writeByte(0x02);//1帧来源+枪号
        }else if("13".equals(frame)) {
            bodyBuffer.writeByte(0x03);//1帧来源+枪号
        }
        bodyBuffer.writeByte(0x01);//应答  0.请求帧，1.应答帧，2.主动上传
        bodyBuffer.writeByte(0x01);//1.心跳确认
        msg.setMsgBody(bodyBuffer);

        ChannelFuture f = e.getChannel().write(msg);
        log.info("响应客户端发送的心跳请求:-设备号:"+deviceNo+"-->枪号:"+qh);
        //f.addListener(ChannelFutureListener.CLOSE);
    }

    //处理客户端对启停指令的响应
    private void receiveResp(ConsuMessage msg) {
        if(msg!=null && msg.getMsgBody()!=null && 
        		StringUtils.isNotBlank(msg.getSource()+"") && 
        		StringUtils.isNotBlank(msg.getDeviceNo()+"")){
            ChannelBuffer body = msg.getMsgBody();
            int source = msg.getSource();//已转成10进制
            int qh = source-16;
            //TODO  判断是否存在该终端号  
        	long bwHexDeviceNo = msg.getDeviceNo();
        	//转16进制
        	String hex = Long.toHexString(bwHexDeviceNo);
        	//高低互换
        	String hlHex = HexUtil.hexHighLow(hex);
        	//16转10
        	Long deviceNo = Long.valueOf(hlHex, 16);
            log.info("启停指令客户端响应数据-终端号:"+deviceNo+"-->枪号:"+qh+"-->指令0x"+Integer.toHexString(msg.getMsgId()));
            if(msg.getMsgId() == EchargeConstants.START_CD_C){
                int transType = body.readByte();
                int state = body.readByte();
                if(state == EchargeConstants.START_SUCCESS_C){
                    //TODO
                    CdzGun cdzGun = new CdzGun();
                    cdzGun.setStakeCode(deviceNo+"");
                    cdzGun.setGunNum(qh+"");
                    cdzGun.setUpdateTime(new Date());
                    cdzGun.setStatus(EchargeConstants.CHARGING_STATUS);//0 充电中
                    boolean res  = cdzGunService.updateStatus(cdzGun);
                    if(res){
                    	log.info("终端号:"+deviceNo+"-->枪号:"+qh+"------------启动充电成功");
                    	//更新订单状态为   0开始充电
                    	UserOrderEntity entity = new UserOrderEntity();
                    	entity.setStakeCode(deviceNo+"");
                    	entity.setGunCode(qh+"");
                    	entity.setUpdateTime(new Date());
                    	entity.setChargeState(charging_status);//订单表  充电中
                    	UserOrderEntityExample example = new UserOrderEntityExample();
                    	UserOrderEntityExample.Criteria criteria = example.createCriteria();
                    	criteria.andDelFlagEqualTo("0");
                    	criteria.andChargeStateEqualTo(not_charging_status);//未充电  
                    	criteria.andStakeCodeEqualTo(deviceNo+"");
                    	criteria.andGunCodeEqualTo(qh+"");
                    	criteria.andPayStateEqualTo("1");//已冻结
                    	example.setOrderByClause("CREATE_TIME DESC");//查找最新的一条未充电的订单
                    	UserOrderEntity userEntity = scanCodeService.getUserOrderEntity(example);
                    	if(userEntity!=null){
                    		entity.setId(userEntity.getId());
                    		boolean r = scanCodeService.updateUserOrderEntityById(entity);
                    		if(r){
                        		//插入一条充电信息
                        		UserOrderEntityExample ex = new UserOrderEntityExample();
                            	UserOrderEntityExample.Criteria cr = ex.createCriteria();
                            	cr.andDelFlagEqualTo("0");
                            	cr.andChargeStateEqualTo(charging_status);//充电中
                            	cr.andStakeCodeEqualTo(deviceNo+"");
                            	cr.andGunCodeEqualTo(qh+"");
                            	cr.andPayStateEqualTo("1");//已冻结
                            	ex.setOrderByClause("CREATE_TIME DESC");
                            	UserOrderEntity e = scanCodeService.getUserOrderEntity(ex);
                            	if(e!=null){
                            		CdzChargingEntity cdzChargingEntity = new CdzChargingEntity();
                            		cdzChargingEntity.setId(e.getId());
                            		cdzChargingEntity.setDelFlag("0");
                            		cdzChargingEntity.setSoc("0");
                            		cdzChargingEntity.setStakeCode(deviceNo+"");
                            		cdzChargingEntity.setGunNum(qh+"");
                            		cdzChargingEntity.setDl("0");
                            		cdzChargingEntity.setDl("0");
                            		cdzChargingEntity.setDy("0");
                            		cdzChargingEntity.setDn("0");
                            		cdzChargingEntity.setTime("0");
                            		cdzChargingEntity.setSyTime("0");
                            		cdzChargingService.insertCdzChargingEntity(cdzChargingEntity);
                            		log.info("-----插入充电信息--------------");
                            		//推送消息到app
                                    CdzAppUser user = cdzAppUserService.selectByPrimaryKey(e.getUserId());
                                    List<Object> registrationIdList = new ArrayList<>();
                                    if (StringUtils.isNotEmpty(user.getDeviceId())) {
                                        registrationIdList.add(user.getDeviceId());
                                        String title = "充电状态改变";
                                        String b = "推送消息到app";
                                        log.info("手机号:"+e.getUserPhone()+"-->设备id:"+user.getDeviceId()+"标题:"+title);
                                        try {
                                            PushUtil.messagePush(registrationIdList, title, b, "1", "", user.getType());
                                        } catch (Exception e2) {
                                            e2.printStackTrace();
                                        }
                                    }
                            	}
                        	}
                    	}
                    	
                    	
                    	//充电中的订单  获取deviceId
                    	//String deviceId = deviceId(deviceNo+"",qh+"",charging_status);
                    }
                }else if(state == EchargeConstants.START_FAIL_C){
                    log.info("------------------启动充电失败,充电状态仍是未充电");
                    //String deviceId = deviceId(deviceNo+"",qh+"",not_charging_status);
                }else if(state == EchargeConstants.STOP_SUCCESS_C){
                	log.info("------------------停止充电成功");
                }else if(state == EchargeConstants.STOP_FAIL_C){
                    log.info("------------------停止充电失败");
                }
            }else{
                log.error("------------------未接受到客户端的响应信息");
            }
        }

    }
    
    
    //处理客户端发送到监控平台的历史数据
    public void handleHistoryData(ConsuMessage msg, ChannelHandlerContext ctx, MessageEvent e,int c) throws Exception{
        ChannelBuffer bodyBuffer = msg.getMsgBody();
        long bwHexDeviceNo = msg.getDeviceNo();
        //转16进制
    	String hex = Long.toHexString(bwHexDeviceNo);
    	//高低互换
    	String hlHex = HexUtil.hexHighLow(hex);
    	Long deviceNo = Long.valueOf(hlHex, 16);
        int source = msg.getSource();
        int qh = source-16;
        log.info("接收客户端发送的历史数据--终端号="+deviceNo+"-->枪号:"+qh+"-->数据体:"+bodyBuffer);
        byte b = bodyBuffer.readByte();//传输类型
        long msgLength = bodyBuffer.readUnsignedShort();
        int cdfs = bodyBuffer.readUnsignedShort();//充电方式
        String cdfs_c = befor(Integer.toHexString(cdfs));//报文数据
        
        byte cdfsL = bodyBuffer.readByte();
        byte cdfsV = bodyBuffer.readByte();
        
        int cdms = bodyBuffer.readUnsignedShort();//充电模式
        String cdms_c = befor(Integer.toHexString(cdms));
        byte cdmsL = bodyBuffer.readByte();
        byte cdmsV = bodyBuffer.readByte();
        
        int cdklx = bodyBuffer.readUnsignedShort();//充电卡类型
        String cdklx_c = befor(Integer.toHexString(cdklx));
        byte cdklxL = bodyBuffer.readByte();
        byte cdklxV = bodyBuffer.readByte();
        
        int cdkh = bodyBuffer.readUnsignedShort();//充电卡号
        String cdkh_c = befor(Integer.toHexString(cdkh));
        byte cdkhL = bodyBuffer.readByte();
        ChannelBuffer  cdkhV = bodyBuffer.readBytes(20);
        /*String phone = cdkhV.readLong()+"";
        String phone = Long.valueOf(cdkhV, 16)+"";
        log.info("历史数据响应充电卡号报文:"+cdkhV+"--十进制值:"+phone);*/
        
        int cl = bodyBuffer.readUnsignedShort();//车辆vin
        byte clL = bodyBuffer.readByte();
        String clV = bodyBuffer.readBytes(17).toString();
        
        int cdqye = bodyBuffer.readUnsignedShort();//充电前余额
        byte cdqyeL = bodyBuffer.readByte();
        String cdqyeV = bodyBuffer.readBytes(4).toString();
        
        /*int cddy = bodyBuffer.readUnsignedShort();//充电电压
        byte cddyL = bodyBuffer.readByte();
        String cddyV = bodyBuffer.readBytes(4).toString();
        
        int cddl = bodyBuffer.readUnsignedShort();//充电电流
        byte cddlL = bodyBuffer.readByte();
        String cddlV = bodyBuffer.readBytes(4).toString();
        
        int cdsj = bodyBuffer.readUnsignedShort();//充电时间  秒
        byte cdsjL = bodyBuffer.readByte();
        String cdsjV = bodyBuffer.readBytes(4).toString();
        
        int cdje = bodyBuffer.readUnsignedShort();//充电 金额
        byte cdjeL = bodyBuffer.readByte();
        String cdjeV = bodyBuffer.readBytes(4).toString();
        
        int cddn = bodyBuffer.readUnsignedShort();//充电 电能
        byte cddnL = bodyBuffer.readByte();
        String cddnV = bodyBuffer.readBytes(4).toString();*/
        int cddy = bodyBuffer.readUnsignedShort();//充电电压
        byte cddyL = bodyBuffer.readByte();
        long cddyV = bodyBuffer.readUnsignedInt();
        long dyV = 0;
        double ddy = 0;
        if(cddyV !=0){
        	String hexcddyV = Long.toHexString(cddyV);
        	String hexcddyV8 = HexUtil.befor0(hexcddyV, 8);
            String dy = HexUtil.hexHighLow(hexcddyV8);
            dyV = Long.valueOf(dy, 16);
            ddy = Double.parseDouble(dyV+"")/10;
            log.info("历史数据电压报文:"+hexcddyV8+"-->高低转换:"+dy+"-->十进制值:"+dyV+"-->一位小数:"+ddy);
        }
        
        int cddl = bodyBuffer.readUnsignedShort();//充电电流
        byte cddlL = bodyBuffer.readByte();
        long cddlV = bodyBuffer.readUnsignedInt();
        long dlV = 0;
        double ddl = 0;
        if(cddlV !=0){
        	String hexcddlV = Long.toHexString(cddlV);
        	String hexcddlV8 = HexUtil.befor0(hexcddlV, 8);
            String dl = HexUtil.hexHighLow(hexcddlV8);
            dlV = Long.valueOf(dl, 16);
            ddl = Double.parseDouble(dlV+"")/100;
            String dl2 = bl2(ddl);
            log.info("历史数据电流报文:"+hexcddlV8+"-->高低转换:"+dl+"-->十进制值:"+dlV+"-->两位小数:"+dl2);
        }
        
        int cdsj = bodyBuffer.readUnsignedShort();//充电时间  秒
        byte cdsjL = bodyBuffer.readByte();
        long cdsjV = bodyBuffer.readUnsignedInt();
        long sjV = 0;
        if(cdsjV !=0){
        	String hexcdsjV = Long.toHexString(cdsjV);
        	String hexcdsjV8 = HexUtil.befor0(hexcdsjV, 8);
            String sj = HexUtil.hexHighLow(hexcdsjV8);
            sjV = Long.valueOf(sj, 16);
            log.info("历史数据充电时间报文:"+hexcdsjV+"-->高低转换:"+sj+"-->十进制值:"+sjV+" 秒");
        }
        
        int cdje = bodyBuffer.readUnsignedShort();//充电 金额
        byte cdjeL = bodyBuffer.readByte();
        long cdjeV = bodyBuffer.readUnsignedInt();
        long jeV = 0;
        double dje = 0;
        if(cdjeV!=0){
        	String hexcdjeV = Long.toHexString(cdjeV);
        	String hexcdjeV8 = HexUtil.befor0(hexcdjeV, 8);
            String je = HexUtil.hexHighLow(hexcdjeV8);
            jeV = Long.valueOf(je, 16);
            dje = Double.parseDouble(jeV+"")/100;
            String dje2 = bl2(dje);
            log.info("历史数据充电金额报文:"+hexcdjeV8+"-->高低转换:"+je+"-->十进制值:"+jeV+"-->两位小数:"+dje2+" 元");
        }
        
        int cddn = bodyBuffer.readUnsignedShort();//充电 电能
        byte cddnL = bodyBuffer.readByte();
        long cddnV = bodyBuffer.readUnsignedInt();
        long dnV = 0;
        double ddn = 0;
        if(cddnV !=0){
        	String hexcddnV = Long.toHexString(cddnV);
        	String hexcddnV8 = HexUtil.befor0(hexcddnV, 8);
            String dn = HexUtil.hexHighLow(hexcddnV8);
            dnV = Long.valueOf(dn, 16);
            ddn = Double.parseDouble(dnV+"")/100;
            String ddn2 = bl2(ddn);
            log.info("历史数据充电电能报文:"+hexcddnV8+"-->高低转换:"+dn+"-->十进制值:"+dnV+"-->两位小数:"+ddn2+" kw/h");
        }
        
        int cdksdn = bodyBuffer.readUnsignedShort();//充电开始电能
        byte cdksdnL = bodyBuffer.readByte();
        String cdksdnV = bodyBuffer.readBytes(4).toString();
        
        int cdjsdn = bodyBuffer.readUnsignedShort();//充电结束电能
        byte cdjsdnL = bodyBuffer.readByte();
        String cdjsdnV = bodyBuffer.readBytes(4).toString();
        
        int sysj = bodyBuffer.readUnsignedShort();//剩余时间
        byte sysjL = bodyBuffer.readByte();
        String sysjV = bodyBuffer.readBytes(4).toString();
        
        int soc = bodyBuffer.readUnsignedShort();//当前soc
        byte socL = bodyBuffer.readByte();
        byte socV = bodyBuffer.readByte();
        
        int sczz = bodyBuffer.readUnsignedShort();//是否上传主站   0没有上传  1上传
        byte sczzL = bodyBuffer.readByte();
        byte sczzV = bodyBuffer.readByte();
        
        int sfff = bodyBuffer.readUnsignedShort();//是否付费   0没有正常付费  1已经付费
        byte sfffL = bodyBuffer.readByte();
        byte sfffV = bodyBuffer.readByte();
        
        
        int zzyy = bodyBuffer.readUnsignedShort();//终止原因   0正常结束  1异常结束
        byte zzyyL = bodyBuffer.readByte();
        byte zzyyV = bodyBuffer.readByte();
        log.info("接收客户端发送的历史数据时--终端号="+deviceNo+"-->枪号:"+qh+"-->充电终止原因:"+zzyyV);
        
        int kssj = bodyBuffer.readUnsignedShort();//充电开始时间
        byte kssjL = bodyBuffer.readByte();
        ChannelBuffer kssjV = bodyBuffer.readBytes(7);//充电开始时间数据
        int year = kssjV.readUnsignedShort();
        String hexYear = Integer.toHexString(year);
        String realYear = HexUtil.hexHighLow(hexYear);
        byte month = kssjV.readByte();
        String hexMonth = Integer.toHexString(month);
        byte day = kssjV.readByte();
        String hexDay = Integer.toHexString(day);
        
        byte hours = kssjV.readByte();
        String hexHours = Integer.toHexString(hours);
        
        byte minute = kssjV.readByte();
        String hexMinute = Integer.toHexString(minute);//分
        
        byte second = kssjV.readByte();
        String hexSecond = Integer.toHexString(minute);//秒
        
        String t = realYear+"-"+hexMonth+"-"+hexDay+" "+hexHours+":"+hexMinute+":"+hexSecond;
        
        log.info("接收客户端发送的历史数据时--终端号="+deviceNo+"-->枪号:"+qh+"-->充电开始时间:"+t);
        
        int jssj = bodyBuffer.readUnsignedShort();//充电结束时间
        byte jssjL = bodyBuffer.readByte();
        ChannelBuffer jssjV = bodyBuffer.readBytes(7);
        
        int year2 = jssjV.readUnsignedShort();
        String hexYear2 = Integer.toHexString(year2);
        String realYear2 = HexUtil.hexHighLow(hexYear2);
        byte month2 = jssjV.readByte();
        String hexMonth2 = Integer.toHexString(month2);
        byte day2 = jssjV.readByte();
        String hexDay2 = Integer.toHexString(day2);
        
        byte hours2 = jssjV.readByte();
        String hexHours2 = Integer.toHexString(hours2);
        
        byte minute2 = jssjV.readByte();
        String hexMinute2 = Integer.toHexString(minute2);//分
        
        byte second2 = jssjV.readByte();
        String hexSecond2 = Integer.toHexString(minute2);//秒
        
        String t2 = realYear2+"-"+hexMonth2+"-"+hexDay2+" "+hexHours2+":"+hexMinute2+":"+hexSecond2;
        
        log.info("接收客户端发送的历史数据时--终端号="+deviceNo+"-->枪号:"+qh+"-->充电结束时间:"+t2);
        int jylsh = bodyBuffer.readUnsignedShort();//交易流水号
        byte jylshL = bodyBuffer.readByte();
        ChannelBuffer jylshV = bodyBuffer.readBytes(4);
        
        int ccxh = bodyBuffer.readUnsignedShort();//存储序号
        byte ccxhL = bodyBuffer.readByte();
        ChannelBuffer ccxhV = bodyBuffer.readBytes(4);
        
        int sjd = bodyBuffer.readUnsignedShort();//充电时间段信息
        byte sjdL = bodyBuffer.readByte();
        String sjdV = bodyBuffer.readBytes(80).toString();
        
        //修改订单结束时间等数据
    	UserOrderEntity entity = new UserOrderEntity();
    	entity.setUpdateTime(new Date());
    	entity.setStartTime(parseDate(t));
    	entity.setEndTime(parseDate(t2));
    	//entity.setChargeDy(ddy+"");//充电电压
    	entity.setChargeDn(bl2(ddn));
    	entity.setEndType(zzyyV+"");
    	entity.setChargeLong(new BigDecimal(sjV));
    	entity.setChargeState("2");//已完成  只要有历史数据，充电状态都为已完成
    	entity.setPayNumberPlan(new BigDecimal(bl2(dje)));
    	//TODO 结束方式和电能
    	String transaction_id="";
    	String outNo = "";
    	String id = "";
    	UserOrderEntityExample example = new UserOrderEntityExample();
    	UserOrderEntityExample.Criteria criteria = example.createCriteria();
    	criteria.andDelFlagEqualTo("0");
    	criteria.andChargeStateIn(Arrays.asList("0","2","4"));//充电中,已完成
    	criteria.andStakeCodeEqualTo(deviceNo+"");
    	criteria.andGunCodeEqualTo(qh+"");
    	criteria.andPayStateEqualTo("1");//已冻结
    	//criteria.andUserPhoneEqualTo(phone);
    	example.setOrderByClause("CREATE_TIME DESC");
    	UserOrderEntity userEntity = scanCodeService.getUserOrderEntity(example);
    	if(userEntity!=null){
    		transaction_id = userEntity.getTradeNo();
    		outNo = userEntity.getOutTradeNo();
    		entity.setId(userEntity.getId());
    		boolean res = scanCodeService.updateUserOrderEntityById(entity);
    		if(res){
    			id = userEntity.getId();
    			log.info("接收客户端发送的历史数据时--终端号="+deviceNo+"-->枪号:"+qh+"-->更新订单的开始充电时间和结束充电时间成功");
    			
    		}
    	}
    	
        //封装历史数据回应指令
        ChannelBuffer body = ChannelBuffers.buffer(23);
        body.writeShort(0x1C00);//长度
        body.writeBytes(HexUtil.hexStringToByte(Long.toHexString(msg.getDeviceNo())));//终端号
        body.writeByte(msg.getMsgId());//历史数据命令
        int s = msg.getSource();
        String frame = Integer.toHexString(s);
        if ("10".equals(frame)) {
        	body.writeByte(0x00);//1帧来源+枪号
        }else if("11".equals(frame)) {
        	body.writeByte(0x01);//1帧来源+枪号
        }else if("12".equals(frame)) {
        	body.writeByte(0x02);//1帧来源+枪号
        }else if("13".equals(frame)) {
        	body.writeByte(0x03);//1帧来源+枪号
        }

        body.writeByte(0x01);//应答  0.请求帧，1.应答帧，2.主动上传
        body.writeShort(0x1800);//
        body.writeBytes(jylshV);//流水号
        body.writeBytes(ccxhV);//存储序号
        body.writeInt(0x00000000);//存储结果
        msg.setMsgBody(body);

        e.getChannel().write(msg);
        //TODO 
        log.info("历史数据响应成功-------");
        
        log.info("充电完成的订单id:"+id);
        if(StringUtils.isNoneBlank(id)){
        	//TODO 调用方法
        	cdzAmountDetailService.endChargeBusiness(id);
        }
        if(userEntity!=null){
        	//推送消息到app
            CdzAppUser user = cdzAppUserService.selectByPrimaryKey(userEntity.getUserId());
            List<Object> registrationIdList = new ArrayList<>();
            if (StringUtils.isNotEmpty(user.getDeviceId())) {
                registrationIdList.add(user.getDeviceId());
                String title = "充电状态改变";
                String bb = "推送消息到app";
                log.info("手机号:"+userEntity.getUserPhone()+"-->设备id:"+user.getDeviceId()+"标题:"+title);
                try {
                    PushUtil.messagePush(registrationIdList, title, bb, "1", "", user.getType());
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }  
        }
        
        
         //退款  TODO  重新做处理
    	/*log.info("终端号:"+deviceNo+"-->枪号:"+qh+"-->支付流水号:"+transaction_id);
    	if(StringUtil.isNotEmpty(outNo)){
    		UserOrderEntity orderEntity =  scanCodeService.selectOrderByOrderNum(outNo);
    		if(orderEntity !=null && "2".equals(orderEntity.getPayState())){
    			BigDecimal amount = orderEntity.getPayNumber();
    			BigDecimal payNumPlan = orderEntity.getPayNumberPlan();
    			if(payNumPlan == null){
    				payNumPlan = BigDecimal.ZERO;
    			}
    			BigDecimal refund_amount = amount.subtract(payNumPlan);
    			if(refund_amount.compareTo(BigDecimal.ZERO)<1){
    				refund_amount = BigDecimal.ZERO;
    			}
    			String userId = orderEntity.getUserId();
    			String orderId = orderEntity.getId();
    			String payType = orderEntity.getPayType();
    			String outTradeNo = orderEntity.getOutTradeNo();
    			
    			String type = "";
    			if(StringUtils.isNotBlank(payType)){
    				if("1".equals(payType)){
    					type = "wx";
    				}else if("0".equals(payType)){
    					type = "zfb";
    				}
    			}
    			CdzOrderRefundEntityExample entityExample = new CdzOrderRefundEntityExample();
    			CdzOrderRefundEntityExample.Criteria cri = entityExample.createCriteria();
    			cri.andDelFlagEqualTo("0");
    			cri.andTradeNoEqualTo(transaction_id);
    			
    			List<CdzOrderRefundEntity> list = cdzOrderRefundService.select(entityExample);
    			if(CollectionUtil.isEmpty(list)){
    				if(refund_amount.compareTo(BigDecimal.ZERO)==1){
    					String uuid = UUID.randomUUID().toString().replace("-", "");
            			payNotifyController.refundRequest(type, transaction_id, refund_amount, amount, userId, outTradeNo, uuid);
    				}
    				
    			}
    			
    		}
    	}*/
    }
    
    
    //处理客户端发送到监控平台的实时数据
    public void handleRealTimeData(ConsuMessage msg, ChannelHandlerContext ctx, MessageEvent e,int c) {
        ChannelBuffer bodyBuffer = msg.getMsgBody();
        long bwHexDeviceNo = msg.getDeviceNo();
        //转16进制
    	String hex = Long.toHexString(bwHexDeviceNo);
    	//高低互换
    	String hlHex = HexUtil.hexHighLow(hex);
    	Long deviceNo = Long.valueOf(hlHex, 16);
        int source = msg.getSource();
        int qh = source-16;
        byte b = bodyBuffer.readByte();//传输类型
        long msgLength = bodyBuffer.readUnsignedShort();
        int cdfs = bodyBuffer.readUnsignedShort();//0306
        String cdfs_c = befor(Integer.toHexString(cdfs));//报文数据
        
        byte cdfsL = bodyBuffer.readByte();
        int cdfsV = bodyBuffer.readUnsignedShort();
        
        int cdms = bodyBuffer.readUnsignedShort();//0406
        String cdms_c = befor(Integer.toHexString(cdms));
        byte cdmsL = bodyBuffer.readByte();
        int cdmsV = bodyBuffer.readUnsignedShort();
        
        int sbzt = bodyBuffer.readUnsignedShort();//设备状态
        String sbzt_c = befor(Integer.toHexString(sbzt));
        byte sbztL = bodyBuffer.readByte();
        byte sbztV = bodyBuffer.readByte();
        
        int cdkh = bodyBuffer.readUnsignedShort();//充电卡号
        String cdkh_c = befor(Integer.toHexString(cdkh));
        byte cdkhL = bodyBuffer.readByte();
        ChannelBuffer  cdckhV = bodyBuffer.readBytes(20);
        /*String phone = cdckhV.readLong()+"";
        String phone = Long.valueOf(cdckhV, 16)+"";
        log.info("充电卡号报文:"+cdckhV+"--十进制值:"+phone);*/
        
        
        int cl = bodyBuffer.readUnsignedShort();//车辆vin
        byte clL = bodyBuffer.readByte();
        String clV = bodyBuffer.readBytes(17).toString();
        
        
        int cddy = bodyBuffer.readUnsignedShort();//充电电压
        byte cddyL = bodyBuffer.readByte();
        long cddyV = bodyBuffer.readUnsignedInt();
        long dyV = 0;
        double ddy = 0;
        if(cddyV !=0){
        	String hexcddyV = Long.toHexString(cddyV);
        	String hexcddyV8 = HexUtil.befor0(hexcddyV, 8);
            String dy = HexUtil.hexHighLow(hexcddyV8);
            dyV = Long.valueOf(dy, 16);
            ddy = Double.parseDouble(dyV+"")/10;
            log.info("电压报文:"+hexcddyV8+"-->高低转换:"+dy+"-->十进制值:"+dyV+"-->一位小数:"+ddy);
        }
        
        int cddl = bodyBuffer.readUnsignedShort();//充电电流
        byte cddlL = bodyBuffer.readByte();
        long cddlV = bodyBuffer.readUnsignedInt();
        long dlV = 0;
        double ddl = 0;
        if(cddlV !=0){
        	String hexcddlV = Long.toHexString(cddlV);
        	String hexcddlV8 = HexUtil.befor0(hexcddlV, 8);
            String dl = HexUtil.hexHighLow(hexcddlV8);
            dlV = Long.valueOf(dl, 16);
            ddl = Double.parseDouble(dlV+"")/100;
            String ddl2 = bl2(ddl);
            log.info("电流报文:"+hexcddlV8+"-->高低转换:"+dl+"-->十进制值:"+dlV+"-->两位小数:"+ddl2);
        }
        
        int cdsj = bodyBuffer.readUnsignedShort();//充电时间  秒
        byte cdsjL = bodyBuffer.readByte();
        long cdsjV = bodyBuffer.readUnsignedInt();
        long sjV = 0;
        if(cdsjV !=0){
        	String hexcdsjV = Long.toHexString(cdsjV);
        	String hexcdsjV8 = HexUtil.befor0(hexcdsjV, 8);
            String sj = HexUtil.hexHighLow(hexcdsjV8);
            sjV = Long.valueOf(sj, 16);
            log.info("充电时间报文:"+hexcdsjV8+"-->高低转换:"+sj+"-->十进制值:"+sjV+" 秒");
        }
        
        int cdje = bodyBuffer.readUnsignedShort();//充电 金额
        byte cdjeL = bodyBuffer.readByte();
        long cdjeV = bodyBuffer.readUnsignedInt();
        long jeV = 0;
        double dje = 0;
        if(cdjeV!=0){
        	String hexcdjeV = Long.toHexString(cdjeV);
        	String hexcdjeV8 = HexUtil.befor0(hexcdjeV, 8);
            String je = HexUtil.hexHighLow(hexcdjeV8);
            jeV = Long.valueOf(je, 16);
            dje = Double.parseDouble(jeV+"")/100;
            String dje2 = bl2(dje);
            log.info("充电金额报文:"+hexcdjeV8+"-->高低转换:"+je+"-->十进制值:"+jeV+"-->两位小数:"+dje2+" 元");
        }
        
        int cddn = bodyBuffer.readUnsignedShort();//充电 电能
        byte cddnL = bodyBuffer.readByte();
        long cddnV = bodyBuffer.readUnsignedInt();
        long dnV = 0;
        double ddn = 0;
        if(cddnV !=0){
        	String hexcddnV = Long.toHexString(cddnV);
        	String hexcddnV8 = HexUtil.befor0(hexcddnV, 8);
            String dn = HexUtil.hexHighLow(hexcddnV8);
            dnV = Long.valueOf(dn, 16);
            ddn = Double.parseDouble(dnV+"")/100;
            String ddn2 = bl2(ddn);
            log.info("充电电能报文:"+hexcddnV8+"-->高低转换:"+dn+"-->十进制值:"+dnV+"-->两位小数:"+ddn2+" kw/h");
        }
        
        
        int sysj = bodyBuffer.readUnsignedShort();//剩余时间
        byte sysjL = bodyBuffer.readByte();
        long sysjV = bodyBuffer.readUnsignedInt();
        long syV = 0;
        if(sysjV !=0){
        	String hexsysjV = Long.toHexString(sysjV);
        	String hexsysjV8 = HexUtil.befor0(hexsysjV, 8);
            String sy = HexUtil.hexHighLow(hexsysjV8);
            syV = Long.valueOf(sy, 16);
            log.info("BMS剩余时间报文:"+hexsysjV8+"-->高低转换:"+sy+"-->十进制值:"+syV);
        }
        int soc = bodyBuffer.readUnsignedShort();//当前soc
        byte socL = bodyBuffer.readByte();
        byte socV = bodyBuffer.readByte();
        
        int jg = bodyBuffer.readUnsignedShort();//警告
        String jg_c = befor(Integer.toHexString(jg));
        byte jgL = bodyBuffer.readByte();
        ChannelBuffer jgV = bodyBuffer.readBytes(8);
        byte v1 = jgV.readByte();
        byte v2 = jgV.readByte();
        byte v3 = jgV.readByte();
        byte v4 = jgV.readByte();
        byte v5 = jgV.readByte();
        byte v6 = jgV.readByte();
        byte v7 = jgV.readByte();
        byte v8 = jgV.readByte();
        warnHandel(v1, v2, v3, v4, v5, v6, v7, v8, deviceNo, qh);
        
        int cdkyex = bodyBuffer.readUnsignedShort();//充电卡余额
        String cdkyex_c = befor(Integer.toHexString(cdkyex));
        byte cdkyexL = bodyBuffer.readByte();
        long cdkyexV = bodyBuffer.readUnsignedInt();
        long cdkyeV = 0;
        double dcdkyexV = 0;
        if(cdkyexV!=0){
        	String hexcdkyexV = Long.toHexString(cdkyexV);
        	String hexcdkyexV8 = HexUtil.befor0(hexcdkyexV, 8);
            String je = HexUtil.hexHighLow(hexcdkyexV8);
            cdkyeV = Long.valueOf(je, 16);
            dcdkyexV = Double.parseDouble(cdkyeV+"")/100;
            String dje2 = bl2(dcdkyexV);
            log.info("充电卡余额报文:"+hexcdkyexV8+"-->高低转换:"+je+"-->十进制值:"+jeV+"-->两位小数:"+dje2+" 元");
        }
        
        int cdklx = bodyBuffer.readUnsignedShort();//充电卡类型
        String cdklx_c = befor(Integer.toHexString(cdklx));
        byte cdklxL = bodyBuffer.readByte();
        byte cdklxV = bodyBuffer.readByte();
        
        int cdf = bodyBuffer.readUnsignedShort();//充电方式
        String cdf_c = befor(Integer.toHexString(cdf));
        byte cdfL = bodyBuffer.readByte();
        byte cdfV = bodyBuffer.readByte();
        
        int cdmode = bodyBuffer.readUnsignedShort();//充电模式
        String cdmode_c = befor(Integer.toHexString(cdmode));
        byte cdmodeL = bodyBuffer.readByte();
        byte cdmodeV = bodyBuffer.readByte();
        log.info("充电模式标识:"+cdmode_c+"-->充电模式:"+cdmodeV);
        long sytime = 0;
        //按时间充计算剩余时间
        /*if(2==cdmodeV){
        	sytime = msg.getTime()-sjV;
        	if(sytime<0){
        		sytime = 0;
        	}
        	log.info("充电时间:"+msg.getTime()+"-->充电剩余时间:"+sytime);
        }*/
        log.info("接收到客户端发送的实时数据时---设备号:"+deviceNo+"-->枪号:"+qh+"设备状态:"+state(sbztV)+"-->soc:"+socV+"-->充电模式:"+cdmodeV);
        //封装响应实时数据
        ChannelBuffer body = ChannelBuffers.buffer(23);
        body.writeShort(0x1100);//长度
        body.writeBytes(HexUtil.hexStringToByte(Long.toHexString(msg.getDeviceNo())));//终端号
        body.writeByte(msg.getMsgId());//历史数据命令
        int s = msg.getSource();
        String frame = Integer.toHexString(s);
        if ("10".equals(frame)) {
        	body.writeByte(0x00);//1帧来源+枪号
        }else if("11".equals(frame)) {
        	body.writeByte(0x01);//1帧来源+枪号
        }else if("12".equals(frame)) {
        	body.writeByte(0x02);//1帧来源+枪号
        }else if("13".equals(frame)) {
        	body.writeByte(0x03);//1帧来源+枪号
        }

        body.writeByte(0x01);//应答    0.请求帧，1.应答帧，2.主动上传
        body.writeShort(0x1300);//
        body.writeByte(0x01);//
        msg.setMsgBody(body);

        e.getChannel().write(msg);
        //TODO 
        log.info("设备号:"+deviceNo+"-->枪号:"+qh+"实时数据响应成功-------");
        //   设备状态为0
        if(sbztV==0 || sbztV==2  || sbztV==3){
        	log.info("接收到客户端发送的实时数据时---设备号:"+deviceNo+"-->枪号:"+qh+"设备状态:"+state(sbztV)+"-->开始更新枪的状态");
        	CdzGun gun = scanCodeService.checkCdzGun(qh+"", deviceNo+"");
        	if(gun!=null){
        		String status = gun.getStatus();
        		CdzGun cdzGun = new CdzGun();
                cdzGun.setStakeCode(deviceNo+"");
                cdzGun.setGunNum(qh+"");
                cdzGun.setUpdateTime(new Date());
                if(sbztV==0){
                	cdzGun.setStatus("2");//空闲
                }else if(sbztV==2){
                	cdzGun.setStatus("0");//充电中
                }else if(sbztV==3){
                	cdzGun.setStatus("3");//已完成
                }
                boolean res  = cdzGunService.updateStatus(cdzGun);
                if(res){
                	log.info("接收到客户端发送的实时数据时---设备号:"+deviceNo+"-->枪号:"+qh+"设备状态:"+state(sbztV)+"-->更新枪的状态---更新成功");
                	//String deviceId = deviceId(deviceNo+"",qh+"",finish_charging_status);
                }
        	}
        	
        }
        if(sbztV==2 || sbztV==3){ //|| sbztV==3
        	//查询充电中的订单
        	UserOrderEntityExample example = new UserOrderEntityExample();
        	UserOrderEntityExample.Criteria criteria = example.createCriteria();
        	criteria.andDelFlagEqualTo("0");
        	criteria.andChargeStateIn(Arrays.asList("0","2","4"));//充电中,已完成
        	criteria.andStakeCodeEqualTo(deviceNo+"");
        	criteria.andGunCodeEqualTo(qh+"");
        	criteria.andPayStateEqualTo("1");//已冻结
        	//criteria.andUserPhoneEqualTo(phone);
        	example.setOrderByClause("CREATE_TIME DESC");
        	UserOrderEntity entity = scanCodeService.getUserOrderEntity(example);
        	if(entity!=null){
        		//更新充电信息表
        		String id = entity.getId();
        		CdzChargingEntity charging = new CdzChargingEntity();
        		charging.setId(id);
        		charging.setSoc(socV+"");
        		charging.setUpdateTime(new Date());
        		charging.setDn(bl2(ddn));
        		charging.setDl(bl2(ddl));
        		charging.setDy(ddy+"");
        		charging.setTime(sjV+"");
        		charging.setUsingMoney(new BigDecimal(bl2(dje)));
        		charging.setFullTime(syV+"");//预计充满时间
        		charging.setSyMoney(new BigDecimal(bl2(dcdkyexV)));
        		int r = cdzChargingService.updateCdzChargingEntityById(charging);
        	}
        }
        //充电完成  把充电中的订单该为充电完成
        /*if(sbztV==3){
        	log.info("接收到客户端发送的实时数据时---设备号:"+deviceNo+"-->枪号:"+qh+"设备状态:"+state(sbztV)+"-->更新订单状态（从充电中改为已完成）");
        	//修改订单状态为 已完成  2
        	UserOrderEntity entity = new UserOrderEntity();
        	entity.setStakeCode(deviceNo+"");
        	entity.setGunCode(qh+"");
        	entity.setUpdateTime(new Date());
        	entity.setChargeState(finish_charging_status);//订单表  充电已完成
        	UserOrderEntityExample example = new UserOrderEntityExample();
        	UserOrderEntityExample.Criteria criteria = example.createCriteria();
        	criteria.andDelFlagEqualTo("0");
        	criteria.andChargeStateIn(Arrays.asList("0","2","4"));//充电中,已完成
        	criteria.andStakeCodeEqualTo(deviceNo+"");
        	criteria.andGunCodeEqualTo(qh+"");
        	criteria.andPayStateEqualTo("1");//已冻结
        	//criteria.andUserPhoneEqualTo(phone);
        	example.setOrderByClause("CREATE_TIME DESC");
        	UserOrderEntity userEntity = scanCodeService.getUserOrderEntity(example);
        	if(userEntity!=null){
        		entity.setId(userEntity.getId());
        		boolean r = scanCodeService.updateUserOrderEntityById(entity);
        		if(r){
            		log.info("接收到客户端发送的实时数据时---设备号:"+deviceNo+"-->枪号:"+qh+"设备状态:"+state(sbztV)+"-->更新订单状态---更新成功");
            		CdzGun cdzGun = new CdzGun();  //注释掉
                    cdzGun.setStakeCode(deviceNo+"");
                    cdzGun.setGunNum(qh+"");
                    cdzGun.setUpdateTime(new Date());
                    cdzGun.setStatus(EchargeConstants.FINISH_CHARGING_STATUS);//3 抢表状态改为已完成
                    boolean res  = cdzGunService.updateStatus(cdzGun);
                    if(res){
                    	String deviceId = deviceId(deviceNo+"",qh+"",finish_charging_status);
                    }
            	}
        	}
        	
        	
        }*/
        
    }
    
    
    //处理客户端发送到监控平台的警告信息数据
    public void handleWarnData(ConsuMessage msg, ChannelHandlerContext ctx, MessageEvent e,int c) {
        ChannelBuffer bodyBuffer = msg.getMsgBody();
        long bwHexDeviceNo = msg.getDeviceNo();
        //转16进制
    	String hex = Long.toHexString(bwHexDeviceNo);
    	//高低互换
    	String hlHex = HexUtil.hexHighLow(hex);
    	Long deviceNo = Long.valueOf(hlHex, 16);
        int source = msg.getSource();
        int qh = source-16;
        byte b = bodyBuffer.readByte();//传输类型
        long msgLength = bodyBuffer.readUnsignedShort();
        
        //警告信息
        int gjd = bodyBuffer.readUnsignedShort();//告警点
        byte gjdL = bodyBuffer.readByte();
        long gjdV = bodyBuffer.readUnsignedInt();
        long sgjdV = 0;
        if(gjdV !=0){
        	String hexgjdV = Long.toHexString(gjdV);//告警点报文
        	String hexgjdV8 = HexUtil.befor0(hexgjdV, 8);
            String lgjd = HexUtil.hexHighLow(hexgjdV8);//高低转换
            sgjdV = Long.valueOf(lgjd, 16);
            log.info("告警点报文:"+hexgjdV8+"-->高低转换:"+lgjd+"-->十进制值:"+sgjdV);
        }
        
        int gjyy = bodyBuffer.readUnsignedShort();//告警原因
        byte gjyyL = bodyBuffer.readByte();
        long gjyyV = bodyBuffer.readUnsignedInt();
        long sgjyyV = 0;
        if(gjyyV !=0){
        	String hexgjdV = Long.toHexString(gjyyV);//告警原因报文
        	String hexgjdV8 = HexUtil.befor0(hexgjdV, 8);
            String lgjyy = HexUtil.hexHighLow(hexgjdV8);//高低转换
            sgjyyV = Long.valueOf(lgjyy, 16);
            log.info("告警原因报文:"+hexgjdV8+"-->高低转换:"+lgjyy+"-->十进制值:"+sgjyyV);
        }
        
        int kssj = bodyBuffer.readUnsignedShort();//告警开始时间
        byte kssjL = bodyBuffer.readByte();
        ChannelBuffer kssjV = bodyBuffer.readBytes(7);//告警开始时间数据
        int year = kssjV.readUnsignedShort();
        String hexYear = Integer.toHexString(year);
        String realYear = HexUtil.hexHighLow(hexYear);
        byte month = kssjV.readByte();
        String hexMonth = Integer.toHexString(month);
        byte day = kssjV.readByte();
        String hexDay = Integer.toHexString(day);
        
        byte hours = kssjV.readByte();
        String hexHours = Integer.toHexString(hours);
        
        byte minute = kssjV.readByte();
        String hexMinute = Integer.toHexString(minute);//分
        
        byte second = kssjV.readByte();
        String hexSecond = Integer.toHexString(minute);//秒
        
        String t = realYear+"-"+hexMonth+"-"+hexDay+" "+hexHours+":"+hexMinute+":"+hexSecond;
        
        log.info("接收客户端发送的告警数据时--终端号="+deviceNo+"-->枪号:"+qh+"-->告警开始时间:"+t);
        
        int jssj = bodyBuffer.readUnsignedShort();//告警结束时间
        byte jssjL = bodyBuffer.readByte();
        ChannelBuffer jssjV = bodyBuffer.readBytes(7);
        
        int year2 = jssjV.readUnsignedShort();
        String hexYear2 = Integer.toHexString(year2);
        String realYear2 = HexUtil.hexHighLow(hexYear2);
        byte month2 = jssjV.readByte();
        String hexMonth2 = Integer.toHexString(month2);
        byte day2 = jssjV.readByte();
        String hexDay2 = Integer.toHexString(day2);
        
        byte hours2 = jssjV.readByte();
        String hexHours2 = Integer.toHexString(hours2);
        
        byte minute2 = jssjV.readByte();
        String hexMinute2 = Integer.toHexString(minute2);//分
        
        byte second2 = jssjV.readByte();
        String hexSecond2 = Integer.toHexString(minute2);//秒
        
        String t2 = realYear2+"-"+hexMonth2+"-"+hexDay2+" "+hexHours2+":"+hexMinute2+":"+hexSecond2;
        
        log.info("接收客户端发送的告警数据时--终端号="+deviceNo+"-->枪号:"+qh+"-->告警结束时间:"+t2);
        
        
        int gjcxsj = bodyBuffer.readUnsignedShort();//告警持续时间
        byte gjcxsjL = bodyBuffer.readByte();
        long gjcxsjV = bodyBuffer.readUnsignedInt();
        long sjcxsjV = 0;
        if(gjcxsjV !=0){
        	String hexgjcxsjV = Long.toHexString(gjcxsjV);//告警点报文
        	String hexgjcxsj8 = HexUtil.befor0(hexgjcxsjV, 8);
            String lgjcxsj = HexUtil.hexHighLow(hexgjcxsj8);//高低转换
            sjcxsjV = Long.valueOf(lgjcxsj, 16);
            log.info("告警持续时间报文:"+hexgjcxsj8+"-->高低转换:"+lgjcxsj+"-->十进制值:"+sjcxsjV);
        }
        
        int yxcd = bodyBuffer.readUnsignedShort();//是否影响充电
        byte yxcdL = bodyBuffer.readByte();
        byte yxcdV = bodyBuffer.readByte();
        
        int zz = bodyBuffer.readUnsignedShort();//是否影响zz
        byte zzL = bodyBuffer.readByte();
        byte zzV = bodyBuffer.readByte();
        
        int jylsh = bodyBuffer.readUnsignedShort();//交易流水号
        byte jylshL = bodyBuffer.readByte();
        ChannelBuffer jylshV = bodyBuffer.readBytes(4);
        //log.info("告警信息交易流水号:"+jylshV.readUnsignedInt()+"-->是否影响充电:"+(0==yxcdV ? "无影响" :"有影响"));
        
        int ccxh = bodyBuffer.readUnsignedShort();//存储序号
        byte ccxhL = bodyBuffer.readByte();
        ChannelBuffer ccxhV = bodyBuffer.readBytes(4);
        //log.info("告警信息序号:"+ccxhV.readUnsignedInt());
        //添加告警信息
        String uuid = UUID.randomUUID().toString().replace("-", "");
        CdzWarn warn = new CdzWarn();
        warn.setId(uuid);
        warn.setDelFlag("0");
        warn.setCreateTime(new Date());
        warn.setGunCode(qh+"");
        warn.setStakeCode(deviceNo+"");
        warn.setStartTime(parseDate(t));
        warn.setEndTime(parseDate(t2));
        warn.setWarnSpot(sgjdV+"");
        warn.setWarnDesc(sgjyyV+"");
        warn.setWarnTime(sjcxsjV+"");
        warn.setIsEffect(yxcdV+"");//是否影响充电
        /*int i = cdzWarnService.insert(warn);
        if(i>0){
        	log.info("保存警告信息成功----------");
        }*/
        
        //封装告警数据回应指令
        ChannelBuffer body = ChannelBuffers.buffer(27);
        body.writeShort(0x1800);//长度
        body.writeBytes(HexUtil.hexStringToByte(Long.toHexString(msg.getDeviceNo())));//终端号
        body.writeByte(msg.getMsgId());//告警数据命令
        int s = msg.getSource();
        String frame = Integer.toHexString(s);
        if ("10".equals(frame)) {
        	body.writeByte(0x00);//1帧来源+枪号
        }else if("11".equals(frame)) {
        	body.writeByte(0x01);//1帧来源+枪号
        }else if("12".equals(frame)) {
        	body.writeByte(0x02);//1帧来源+枪号
        }else if("13".equals(frame)) {
        	body.writeByte(0x03);//1帧来源+枪号
        }

        body.writeByte(0x01);//应答  0.请求帧，1.应答帧，2.主动上传
        body.writeShort(0x1300);//
        body.writeBytes(jylshV);
        body.writeBytes(ccxhV);
        
        msg.setMsgBody(body);

        e.getChannel().write(msg);
        //TODO 
        log.info("告警数据响应成功-------");
        
        
    }
    
    //封装费率
    private void fl(ConsuMessage msg, ChannelHandlerContext ctx, MessageEvent e,int c) {
    	long bwHexDeviceNo = msg.getDeviceNo();
        //转16进制
    	String hexdev = Long.toHexString(bwHexDeviceNo);
    	//高低互换
    	String hlHex = HexUtil.hexHighLow(hexdev);
    	Long deviceNo = Long.valueOf(hlHex, 16);
    	//根据桩号查询站号，站号拿到rates值，查询费率
        CdzStake cdzStake = cdzStakeService.getCdzStakeByStakeCode(deviceNo.toString());
        CdzStation cdzStation = cdzStationService.getCdzStation(cdzStake.getStationId());
        /*CdzStation  station = new CdzStation();
    	station.setNum(deviceNo+"");
    	station.setDelFlag("0");*/
    	String rates = "";
    	float f = 1.5f;
    	/*List<CdzStation> stations = cdzStationService.selectCdzStationAll(station);
    	if(CollectionUtils.isNotEmpty(stations)){
    		rates = stations.get(0).getRates();
    	}*/
    	if (null != cdzStation){
    	    rates = cdzStation.getRates();
        }
    	if(StringUtil.isNotEmpty(rates)){
    		CdzRates rate = cdzRatesService.getCdzRates(rates);
    		if(rate!=null && rate.getDirectElectric()!=null){
    			BigDecimal serve = rate.getServe();
    			if(serve==null){
    				serve  = BigDecimal.ZERO;
    			}
    			f = rate.getDirectElectric().floatValue()+serve.floatValue();
    		}
    	}
    	log.info("设备号:"+deviceNo+"-->费率:"+f);
        
        ChannelBuffer bodyBuffer = ChannelBuffers.buffer(140);
        bodyBuffer.writeShort(0x8800);//长度
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(Long.toHexString(msg.getDeviceNo())));//终端号
        bodyBuffer.writeByte(msg.getMsgId());//命令
        int s = msg.getSource();
        int qh = s-16;
        String frame = Integer.toHexString(s);
        if ("10".equals(frame)) {
            bodyBuffer.writeByte(0x00);//1帧来源+枪号
        }else if("11".equals(frame)) {
            bodyBuffer.writeByte(0x01);//1帧来源+枪号
        }else if("12".equals(frame)) {
            bodyBuffer.writeByte(0x02);//1帧来源+枪号
        }else if("13".equals(frame)) {
            bodyBuffer.writeByte(0x03);//1帧来源+枪号
        }
        String hex = Integer.toHexString(Float.floatToIntBits(f));
        String hex8 = HexUtil.befor0(hex, 8);
        String fl = HexUtil.hexHighLow(hex8);
        bodyBuffer.writeByte(0x00);//应答  0.请求帧，1.应答帧，2.主动上传
        bodyBuffer.writeShort(0x1400);//单元个数
        bodyBuffer.writeShort(0x1500);//第一阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        bodyBuffer.writeShort(0x1600);//第二阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        bodyBuffer.writeShort(0x1700);//第3阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        bodyBuffer.writeShort(0x1800);//第4阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        bodyBuffer.writeShort(0x1900);//第5阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        bodyBuffer.writeShort(0x1A00);//第6阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        
        bodyBuffer.writeShort(0x1B00);//第7阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        
        bodyBuffer.writeShort(0x1C00);//第8阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        
        bodyBuffer.writeShort(0x1D00);//第9阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        
        bodyBuffer.writeShort(0x1E00);//第10阶段
        bodyBuffer.writeByte(0x04);
        bodyBuffer.writeBytes(HexUtil.hexStringToByte(fl));//0.9
        
        bodyBuffer.writeShort(0x1F00);//第一阶段开始时间
        bodyBuffer.writeByte(0x02);//长度
        bodyBuffer.writeShort(0x0000);//00:00
        
        bodyBuffer.writeShort(0x2000);//第2阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x0300);//03:00
        
        bodyBuffer.writeShort(0x2100);//第3阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x0600);//06:00
        
        bodyBuffer.writeShort(0x2200);//第4阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x0900);//09:00
        
        bodyBuffer.writeShort(0x2300);//第5阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x0C00);//12:00
        
        bodyBuffer.writeShort(0x2400);//第6阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x0F00);//15:00
        
        bodyBuffer.writeShort(0x2500);//第7阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x1200);//18:00
        
        bodyBuffer.writeShort(0x2600);//第8阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x1500);//21:00
        
        bodyBuffer.writeShort(0x2700);//第9阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x1700);//23:00
        
        bodyBuffer.writeShort(0x2800);//第10阶段开始时间
        bodyBuffer.writeByte(0x02);
        bodyBuffer.writeShort(0x1800);//24:00
        
        msg.setMsgBody(bodyBuffer);

        e.getChannel().write(msg);
        log.info("响应客户端的费率请求-----------");

    }
    
    
    public String deviceId(String deviceNo,String qh,String status){
    	String deviceId = "";
    	String phone = "";
    	UserOrderEntityExample example = new UserOrderEntityExample();
    	UserOrderEntityExample.Criteria criteria = example.createCriteria();
    	criteria.andDelFlagEqualTo("0");
    	criteria.andChargeStandardEqualTo(status);
    	criteria.andStakeCodeEqualTo(deviceNo+"");
    	criteria.andGunCodeEqualTo(qh+"");
    	criteria.andPayStateEqualTo("1");//已冻结
    	example.setOrderByClause("CREATE_TIME DESC");
    	UserOrderEntity e = scanCodeService.getUserOrderEntity(example);
		if(e!=null){
			phone = e.getUserPhone();
			if(StringUtils.isNotBlank(phone)){
				CdzAppUser user = cdzAppUserService.getAppUserByPhone(phone);
				if(user!=null){
					deviceId = user.getDeviceId();
					log.info("手机号="+phone+"-->对应的设备id=="+deviceId);
				}
			}
		}
    	return deviceId;
    }
    
   public String befor(String s){
    	StringBuffer buffer = new StringBuffer();
		if(s.length()==1){
			buffer.append("000");
			buffer.append(s);
		}else if(s.length()==2){
			buffer.append("00");
			buffer.append(s);
		}else if(s.length()==3){
			buffer.append("0");
			buffer.append(s);
		}else if(s.length()==0){
			buffer.append("0000");
		}
		
		return  buffer.toString();
		
	}
   
   public  String state(byte b){
	   if(b==0){
		   return "空闲";
	   }
	   if(b==1){
		   return "连接中";
	   }
	   if(b==2){
		   return "充电中";
	   }
	   if(b==3){
		   return "充电完成";
	   }
	   if(b==4){
		   return "被预约";
	   }
	   if(b==5){
		   return "排队中";
	   }
	   
	return "";
   }
   
   
   
   public Date parseDate(String time){
	   Date date = new Date();
	   SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	   try {
		   date = sf.parse(time);
	} catch (Exception e) {
		e.printStackTrace();
	}
	   return date;
   }
   
   
   public String bl2(double d){
	   BigDecimal bd = new BigDecimal(d);
       bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
       return bd.toString();
   }
   
   
   public static void main(String[] args) throws Exception{
	   /*String time = "2019-5-05 16:24:45";
	   SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	   Date date = sf.parse(time);
	   String s = sf.format(date);
	   System.out.println(s);*/
	  /* double d = 1.2;
	   BigDecimal bd = new BigDecimal(d);
       bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
       System.out.println(bd.toString());
       
       float f = Float.intBitsToFloat(Integer.parseInt("3f666666",16));
       System.out.println(f);
       String s = Integer.toHexString(Float.floatToIntBits(1.5f));
       System.out.println(s);
       
       float w = 0.9f;
       String hex = Integer.toHexString(Float.floatToIntBits(w));
       System.out.println(".........."+hex);
       String hex8 = HexUtil.befor0(hex, 8);
       System.out.println("----"+hex8);
       String fl = HexUtil.hexHighLow(hex8);
       System.out.println("===="+fl);
       
       String ss = fl.substring(0, 8);
       System.out.println(ss);
       
       
       BigDecimal dd = new BigDecimal(9.86);
       System.out.println(dd.shortValue());
       
       long l = Long.valueOf("0000000425319387", 16);
       System.out.println(l);*/
	   BigDecimal bd = new BigDecimal(150.005);
       bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
       System.out.println(bd);
   }
   
   public void warnHandel(byte v1,byte v2,byte v3,byte v4,byte v5,byte v6,byte v7,byte v8,long deviceNo,long qh){
	   byte b1 = (byte) (v1 & 0xff);
	   String s1 = BitUtil.byteToBit(b1);
	   log.info("第1个字节接收到十进制值:"+v1+"-->二进制字符串:"+s1);
	   String p1_1 = s1.substring(7);//触摸屏
	   String s1_1 = "1-1";
	   int v1_1 = Integer.parseInt(p1_1,2);
	   insertAndUpdate(deviceNo,qh,s1_1,v1_1);
	   
	   
	   String p1_2 = s1.substring(6,7);//读卡器
	   String s1_2 = "1-2";
	   int v1_2 = Integer.parseInt(p1_2,2);
	   insertAndUpdate(deviceNo,qh,s1_2,v1_2);
	   
	   
	   String p1_3_4 = s1.substring(4,6);//打印机
	   String s1_3_4 = "1-3.4";
	   int v1_3_4 = Integer.parseInt(p1_3_4,2);
	   insertAndUpdate(deviceNo,qh,s1_3_4,v1_3_4);
	   
	   
	   String p1_5 = s1.substring(3,4);//电能表
	   String s1_5 = "1-5";
	   int v1_5 = Integer.parseInt(p1_5,2);
	   insertAndUpdate(deviceNo,qh,s1_5,v1_5);
	   
	   
	   String p1_6_7_8 = s1.substring(0,3);//链接
	   String s1_6_7_8 = "1-6.7.8";
	   int v1_6_7_8 = Integer.parseInt(p1_6_7_8,2);
	   insertAndUpdate(deviceNo,qh,s1_6_7_8,v1_6_7_8);
	   
	   
	   
	   byte b2 = (byte) (v2 & 0xff);
	   String s2 = BitUtil.byteToBit(b2);
	   log.info("第2个字节接收到十进制值:"+v2+"-->二进制字符串:"+s2);
	   
	   String p2_1_2 = s2.substring(6);//A相
	   String s2_1_2 = "2-1.2";
	   int v2_1_2 = Integer.parseInt(p2_1_2,2);
	   insertAndUpdate(deviceNo,qh,s2_1_2,v2_1_2);
	   
	   
	   String p2_3_4 = s2.substring(4,6);//b相
	   String s2_3_4 = "2-3.4";
	   int v2_3_4 = Integer.parseInt(p2_3_4,2);
	   insertAndUpdate(deviceNo,qh,s2_3_4,v2_3_4);
	   
	   String p2_5_6 = s2.substring(2,4);//c相
	   String s2_5_6 = "2-5.6";
	   int v2_5_6 = Integer.parseInt(p2_5_6,2);
	   insertAndUpdate(deviceNo,qh,s2_5_6,v2_5_6);
	   
	   String p2_7_8 = s2.substring(0,2);//输出过流
	   String s2_7_8 = "2-7.8";
	   int v2_7_8 = Integer.parseInt(p2_7_8,2);
	   insertAndUpdate(deviceNo,qh,s2_7_8,v2_7_8);
	   
	   
	   byte b3 = (byte) (v3 & 0xff);
	   String s3 = BitUtil.byteToBit(b3);
	   log.info("第3个字节接收到十进制值:"+v3+"-->二进制字符串:"+s3);
	   
	   String p3_1 = s3.substring(7);//急停
	   String s3_1 = "3-1";
	   int v3_1 = Integer.parseInt(p3_1,2);
	   insertAndUpdate(deviceNo,qh,s3_1,v3_1);
	   
	   String p3_2 = s3.substring(6,7);//防雷器
	   String s3_2 = "3-2";
	   int v3_2 = Integer.parseInt(p3_2,2);
	   insertAndUpdate(deviceNo,qh,s3_2,v3_2);
	   
	   String p3_3 = s3.substring(5,6);//电池连接状态
	   String s3_3 = "3-3";
	   int v3_3 = Integer.parseInt(p3_3,2);
	   insertAndUpdate(deviceNo,qh,s3_3,v3_3);
	   
	   String p3_4 = s3.substring(4,5);//充电机监控通讯
	   String s3_4 = "3-4";
	   int v3_4 = Integer.parseInt(p3_4,2);
	   insertAndUpdate(deviceNo,qh,s3_4,v3_4);
	   
	   String p3_5_6 = s3.substring(2,4);//直流母线绝缘
	   String s3_5_6 = "3-5.6";
	   int v3_5_6 = Integer.parseInt(p3_5_6,2);
	   insertAndUpdate(deviceNo,qh,s3_5_6,v3_5_6);
	   
	   String p3_7_8 = s3.substring(0,2);//单体电池
	   String s3_7_8 = "3-7.8";
	   int v3_7_8 = Integer.parseInt(p3_7_8,2);
	   insertAndUpdate(deviceNo,qh,s3_7_8,v3_7_8);
	   
	   byte b4 = (byte) (v4 & 0xff);
	   String s4 = BitUtil.byteToBit(b4);
	   log.info("第4个字节接收到十进制值:"+v4+"-->二进制字符串:"+s4);
	   
	   String p4_1 = s4.substring(7);//风扇
	   String s4_1 = "4-1";
	   int v4_1 = Integer.parseInt(p4_1,2);
	   insertAndUpdate(deviceNo,qh,s4_1,v4_1);
	   
	   String p4_2 = s4.substring(6,7);//温度传感器
	   String s4_2 = "4-2";
	   int v4_2 = Integer.parseInt(p4_2,2);
	   insertAndUpdate(deviceNo,qh,s4_2,v4_2);
	   
	   String p4_3 = s4.substring(5,6);//系统温度
	   String s4_3 = "4-3";
	   int v4_3 = Integer.parseInt(p4_3,2);
	   insertAndUpdate(deviceNo,qh,s4_3,v4_3);
	   
	   String p4_4 = s4.substring(4,5);//BMS通讯
	   String s4_4 = "4-4";
	   int v4_4 = Integer.parseInt(p4_4,2);
	   insertAndUpdate(deviceNo,qh,s4_4,v4_4);
	   
	   byte b5 = (byte) (v5 & 0xff);
	   String s5 = BitUtil.byteToBit(b5);
	   log.info("第5个字节接收到十进制值:"+v5+"-->二进制字符串:"+s5);
	   
	   String p5_1 = s5.substring(7);//交流输入欠压
	   String s5_1 = "5-1";
	   int v5_1 = Integer.parseInt(p5_1,2);
	   insertAndUpdate(deviceNo,qh,s5_1,v5_1);
	   
	   String p5_2 = s5.substring(6,7);//交流输入过压
	   String s5_2 = "5-2";
	   int v5_2 = Integer.parseInt(p5_2,2);
	   insertAndUpdate(deviceNo,qh,s5_2,v5_2);
	   
	   String p5_3 = s5.substring(5,6);//输出过压
	   String s5_3 = "5-3";
	   int v5_3 = Integer.parseInt(p5_3,2);
	   insertAndUpdate(deviceNo,qh,s5_3,v5_3);
	   
	   String p5_4 = s5.substring(4,5);//充电模块监控响应超时
	   String s5_4 = "5-4";
	   int v5_4 = Integer.parseInt(p5_4,2);
	   insertAndUpdate(deviceNo,qh,s5_4,v5_4);
	   
	   String p5_5 = s5.substring(3,4);//模块通信中断
	   String s5_5 = "5-5";
	   int v5_5 = Integer.parseInt(p5_5,2);
	   insertAndUpdate(deviceNo,qh,s5_5,v5_5);
	   
	   String p5_6 = s5.substring(2,3);//交流输入欠压
	   String s5_6 = "5-6";
	   int v5_6 = Integer.parseInt(p5_6,2);
	   insertAndUpdate(deviceNo,qh,s5_6,v5_6);
	   
	   String p5_7 = s5.substring(1,2);//模块故障
	   String s5_7 = "5-7";
	   int v5_7 = Integer.parseInt(p5_7,2);
	   insertAndUpdate(deviceNo,qh,s5_7,v5_7);
	   
	   String p5_8 = s5.substring(0,1);//模块保护
	   String s5_8 = "5-8";
	   int v5_8 = Integer.parseInt(p5_8,2);
	   insertAndUpdate(deviceNo,qh,s5_8,v5_8);
	   
	   byte b6 = (byte) (v6 & 0xff);
	   String s6 = BitUtil.byteToBit(b6);
	   log.info("第6个字节接收到十进制值:"+v6+"-->二进制字符串:"+s6);
	   
	   String p6_1 = s6.substring(7);//充电枪故障
	   String s6_1 = "6-1";
	   int v6_1 = Integer.parseInt(p6_1,2);
	   insertAndUpdate(deviceNo,qh,s6_1,v6_1);
	   
	   String p6_2 = s6.substring(6,7);//握手超时
	   String s6_2 = "6-2";
	   int v6_2 = Integer.parseInt(p6_2,2);
	   insertAndUpdate(deviceNo,qh,s6_2,v6_2);
	   
	   String p6_3 = s6.substring(5,6);//配置超时
	   String s6_3 = "6-3";
	   int v6_3 = Integer.parseInt(p6_3,2);
	   insertAndUpdate(deviceNo,qh,s6_3,v6_3);
	   
	   String p6_4 = s6.substring(4,5);//接收充电请求指令超时
	   String s6_4 = "6-4";
	   int v6_4 = Integer.parseInt(p6_4,2);
	   insertAndUpdate(deviceNo,qh,s6_4,v6_4);
	   
	   String p6_5 = s6.substring(3,4);//模块交流缺相告警
	   String s6_5 = "6-5";
	   int v6_5 = Integer.parseInt(p6_5,2);
	   insertAndUpdate(deviceNo,qh,s6_5,v6_5);
	   
	   String p6_6 = s6.substring(2,3);//模块严重不均流
	   String s6_6 = "6-6";
	   int v6_6 = Integer.parseInt(p6_6,2);
	   insertAndUpdate(deviceNo,qh,s6_6,v6_6);
	   
	   String p6_7 = s6.substring(1,2);//门禁开关告警
	   String s6_7 = "6-7";
	   int v6_7 = Integer.parseInt(p6_7,2);
	   insertAndUpdate(deviceNo,qh,s6_7,v6_7);
	   
	   String p6_8 = s6.substring(0,1);//电池异常
	   String s6_8 = "6-8";
	   int v6_8 = Integer.parseInt(p6_8,2);
	   insertAndUpdate(deviceNo,qh,s6_8,v6_8);
	   
	   byte b7 = (byte) (v7 & 0xff);
	   String s7 = BitUtil.byteToBit(b7);
	   log.info("第7个字节接收到十进制值:"+v7+"-->二进制字符串:"+s7);
	   String p7_1 = s7.substring(7);//系统倾倒或严重振动
	   String s7_1 = "7-1";
	   int v7_1 = Integer.parseInt(p7_1,2);
	   insertAndUpdate(deviceNo,qh,s7_1,v7_1);
	   
	   String p7_2 = s7.substring(6,7);//充电枪连接异常
	   String s7_2 = "7-2";
	   int v7_2 = Integer.parseInt(p7_2,2);
	   insertAndUpdate(deviceNo,qh,s7_2,v7_2);
	   
	   String p7_3 = s7.substring(5,6);//放电电阻异常
	   String s7_3 = "7-3";
	   int v7_3 = Integer.parseInt(p7_3,2);
	   insertAndUpdate(deviceNo,qh,s7_3,v7_3);
	   
	   String p7_4 = s7.substring(4,5);//枪头温度过高
	   String s7_4 = "7-4";
	   int v7_4 = Integer.parseInt(p7_4,2);
	   insertAndUpdate(deviceNo,qh,s7_4,v7_4);
	   
	   String p7_5 = s7.substring(3,4);//K1接触器异常
	   String s7_5 = "7-5";
	   int v7_5 = Integer.parseInt(p7_5,2);
	   insertAndUpdate(deviceNo,qh,s7_5,v7_5);
	   
	   String p7_6 = s7.substring(2,3);//系统输出过流
	   String s7_6 = "7-6";
	   int v7_6 = Integer.parseInt(p7_6,2);
	   insertAndUpdate(deviceNo,qh,s7_6,v7_6);
	   
	   String p7_7 = s7.substring(1,2);//U3-U3通讯异常
	   String s7_7 = "7-7";
	   int v7_7 = Integer.parseInt(p7_7,2);
	   insertAndUpdate(deviceNo,qh,s7_7,v7_7);
	   
	   String p7_8 = s7.substring(0,1);//电子锁异常
	   String s7_8 = "7-8";
	   int v7_8 = Integer.parseInt(p7_8,2);
	   insertAndUpdate(deviceNo,qh,s7_8,v7_8);
	   
   }
   
   public void insertAndUpdate(long deviceNo,long qh,String warnSpot,int warnDesc){
	   if(warnDesc == 0){//该告警点正常
		   CdzWarn warn = new CdzWarn();
		   warn.setStakeCode(deviceNo+"");
		   warn.setGunCode(qh+"");
		   warn.setWarnSpot(warnSpot);
		   warn.setStartTime(new Date());
		   List<CdzWarn> list = cdzWarnService.selectCdzWarn(warn);
		   if(CollectionUtil.isNotEmpty(list)){
			   Date endTime = list.get(0).getEndTime();
 			   Date startTime = list.get(0).getStartTime();
 			   if(endTime==null){//没有结束时间，需要更新
 				   //存在一条这样的告警信息
 				   String id = list.get(0).getId();
 				   CdzWarn w = new CdzWarn();
 				   w.setId(id);
 				   endTime = new Date();
 				   long time = (endTime.getTime()-startTime.getTime())/1000;
 				   w.setUpdateTime(endTime);
 				   w.setEndTime(endTime);
 				   w.setWarnTime(time+"");
 				   w.setIsEffect("1");
 				   cdzWarnService.updateByPrimaryKey(w);
 			   }
		   }
	   }else{
		   CdzWarn warn = new CdzWarn();
		   warn.setStakeCode(deviceNo+"");
		   warn.setGunCode(qh+"");
		   warn.setWarnSpot(warnSpot);
		   warn.setWarnDesc(warnDesc+"");
		   List<CdzWarn> list = cdzWarnService.selectCdzWarn(warn);
		   if(CollectionUtil.isNotEmpty(list)){
			   Date endTime = list.get(0).getEndTime();
			   if(endTime != null){//查询出的记录是已恢复告警的，本次需要再新增一条告警记录
				   CdzWarn cdzWarn = new CdzWarn();
				   cdzWarn.setId(IdGenerator.generateId());
				   cdzWarn.setStakeCode(deviceNo+"");
				   cdzWarn.setGunCode(qh+"");
				   cdzWarn.setWarnSpot(warnSpot);
				   cdzWarn.setWarnDesc(warnDesc+"");
				   cdzWarn.setStartTime(new Date());
				   cdzWarn.setCreateTime(new Date());
				   cdzWarnService.insert(cdzWarn);
			   }
		   }else{
			   //数据为空
			   if(warnDesc!=0){//非正常插入一条记录
				   CdzWarn cdzWarn = new CdzWarn();
				   cdzWarn.setId(IdGenerator.generateId());
				   cdzWarn.setStakeCode(deviceNo+"");
				   cdzWarn.setGunCode(qh+"");
				   cdzWarn.setWarnSpot(warnSpot);
				   cdzWarn.setWarnDesc(warnDesc+"");
				   cdzWarn.setStartTime(new Date());
				   cdzWarn.setCreateTime(new Date());
				   cdzWarnService.insert(cdzWarn);
			   }
		   }
	   }
	   
   }
   

}
